import router from './router'
import store from './store'
import NProgress from 'nprogress' // Progress 进度条
import 'nprogress/nprogress.css'// Progress 进度条样式
import {Message} from 'element-ui'
import {getToken} from '@/utils/auth' // 验权
const whiteList = ['/login'] // 不重定向白名单
import SxMenuApi from '@/api/manage/SxMenuApi'
// 后台管理子组件
import Layout from './views/layout/Layout'

/**
 * 路由前置导航
 */
router.beforeEach((to, from, next) => {
  NProgress.start()
  const token = getToken()
  if (token) {
    if (to.path === '/login') {
      next()
      //next({ path: '/' })
      NProgress.done() // if current page is dashboard will not trigger	afterEach hook, so manually handle it
    } else {
      if (router.options.isAddDynamicMenuRoutes) {
        next()
      } else {
        if (store.getters.roles.length === 0) {
          store.dispatch('GetInfo').then(res => { // 拉取用户信息

          }).catch((err) => {
            store.dispatch('FedLogOut').then(() => {
              Message.error(err || 'Verification failed, please login again')
              next({path: '/'})
            })
          })
        } else {
          next()
        }
        SxMenuApi.nav({}).then((data) => {
          debugger
          let children = fnAddDynamicMenuRoutes(data)
          store.commit('SET_ROUTERS', children)
          console.log(children)
          router.addRoutes(children)
          router.options.isAddDynamicMenuRoutes = true
          next({...to, replace: true})
        })
      }


    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/login?redirect=${to.path}`) // 否则全部重定向到登录页
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done() // 结束Progress
})

function fnAddDynamicMenuRoutes (menuList = [], routes = []) {
  let temp = []
  for (let i = 0; i < menuList.length; i++) {
    if (menuList[i].url && /\S/.test(menuList[i].url)) {
      var route;
      if (menuList[i].type === 0) {
        route = {
          path: menuList[i].url,
          component: Layout,
          redirect: '/dashboard',
          alwaysShow: true,
          name: menuList[i].url.replace('/', '-'),
          meta: {
            menuId: menuList[i].id,
            title: menuList[i].name,
            icon: 'example'
          },
          hidden: !menuList[i].isShow
        }
        if (menuList[i].list && menuList[i].list.length >= 1) {
          route.children = fnAddDynamicMenuRoutes(menuList[i].list)
        }
      } else {
        route = {
          path: menuList[i].url,
          name: menuList[i].url.replace('/', '-'),
          meta: {
            menuId: menuList[i].id,
            title: menuList[i].name
          },
          hidden: !menuList[i].isShow
        }
        if (!menuList[i].url.startsWith("http")) {
          route['component'] = () => import('@/views/manage/' + menuList[i].vuePath) || null
        }
      }
      temp.push(route)
    }
  }

  return temp

}
